/**
 * 3η ΓΕ 2013-2014 - Super Market
 * ΦΡΑΓΚΟΥΛΟΠΟΥΛΟΥ ΕΜΜΑΝΟΥΕΛΑ (69298)
 * ΧΑΛΔΑΣ ΧΑΡΑΛΑΜΠΟΣ (69305)
 * ΧΟΡΜΟΒΙΤΗΣ ΙΩΑΝΝΗΣ (69325)
 * ΧΟΥΣΤΟΥΛΑΚΗ ΕΥΑΓΓΕΛΙΑ (69327)
 */
package simulation;

import authority.CreditCardAuthority;
import java.util.List;
import javax.persistence.TypedQuery;
import model.*;
import supermarket.EntityManagerFactory;

/**
 * Class Αρχής Πιστοποίησης
 */
public class CCAuthority {
    
    private final int MAX_CONNECTIONS = 2;
    private int availableConnections;


    public CCAuthority() {
        availableConnections = MAX_CONNECTIONS;
    }

    public synchronized Boolean connect() {
        if( this.availableConnections > 0 ){
           this.availableConnections--;
           return true;
        } 
        else {
           return false;
        }
    }

    public synchronized void disconnect() {
        this.availableConnections++;
    }


        
    public synchronized Boolean validateCard(Purchase p){

        TypedQuery<CreditCardAuthority> q = EntityManagerFactory.
                getEntityManager().createQuery(
                "SELECT c from CreditCardAuthority c where " +
                        " c.cvv='" + p.getCustomer().getCvv() +
                        "' AND c.number='" + p.getCustomer().getCreditCardNum() +
                        "' AND c.ownerName='" + p.getCustomer().getOwner() + "'",
                CreditCardAuthority.class);

        List<CreditCardAuthority> ls = q.getResultList();
        for (int i=0;i<ls.size();++i) {
            if (ls.get(i).getBank().getName().equals(p.getCustomer().getBank()))
                return true;
        }
        return false;
    }
}
